package com.xnyzc.lhy.statistics.service.impl.capacity;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.entity.ParameterEnum;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.statistics.ECapacityType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.DateUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.order.entity.user.OaDUserInfo;
import com.xnyzc.lhy.statistics.eenum.ECapacityOption;
import com.xnyzc.lhy.statistics.entity.param.capacity.CapacityParam;
import com.xnyzc.lhy.statistics.entity.result.capacity.CapacityResult;
import com.xnyzc.lhy.statistics.entity.result.capacity.TransportCapacityLineChart;
import com.xnyzc.lhy.statistics.entity.statistics.ActiveDriver;
import com.xnyzc.lhy.statistics.entity.statistics.CollectCapacityStatistical;
import com.xnyzc.lhy.statistics.mapper.statistics.CollectCapacityStatisticalMapper;
import com.xnyzc.lhy.statistics.mapper.user.OaDUserInfoMapper;
import com.xnyzc.lhy.statistics.service.capacity.CapacityService;
import com.xnyzc.lhy.statistics.service.capacity.OrderSummaryService;
import com.xnyzc.lhy.statistics.service.search.CapacitySearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 运力统计
 * </p>
 *
 * @author wangshuo
 * @since 2019-11-28
 */
@Slf4j
@Service
public class CapacityServiceImpl implements CapacityService {

    @Autowired
    private RedisCommon redisCommon;

    @Autowired
    private OaDUserInfoMapper oaDUserInfoMapper;

    @Autowired
    private CollectCapacityStatisticalMapper collectCapacityStatisticalMapper;

    @Autowired
    private CapacitySearchService capacitySearchService;

    @Autowired
    private OrderSummaryService orderSummaryService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 获取实时运力数据
     * @return
     */
    @Override
    public Rv getCapacityStatistical(CapacityParam capacityParam) {

        // 定义返回结果集
        List<CapacityResult> resultList=new ArrayList<>();
        List<CapacityResult> summerResults = new ArrayList<>();

        // 统计出车司机数量（计算占比使用）
        List<Long> driveOutAccount = collectCapacityStatisticalMapper.driveOutAccount(capacityParam);
        Integer driverOutCount = collectCapacityStatisticalMapper.driveOutAccountAbstrct(capacityParam.getCityId(), driveOutAccount);

        // 准备计算出车司机数量
        if (CheckUtil.objIsEmpty(driverOutCount)) {
            driverOutCount = 0;
        }

        CapacityResult driveOut = new CapacityResult();
        driveOut.setType(ECapacityType.driveOut.getType());
        driveOut.setName(ECapacityType.driveOut.getValue());
        driveOut.setValue(driveOutAccount.size() + driverOutCount);

        Integer driverCount = collectCapacityStatisticalMapper.queryDriverCount();

        if (CheckUtil.objIsEmpty(driverCount)) {
            driverCount = 0;
        }

        CapacityResult driveCountResult = new CapacityResult();
        driveCountResult.setValue(driverCount);

        // 听单中司机
        QueryWrapper<OaDUserInfo> queryListen = new QueryWrapper<>();
        queryListen.eq(OaDUserInfo.ACCEPTANC_ORDER_STATUS, ParameterEnum.ONE.getType());
        if (CheckUtil.objIsNotEmpty(capacityParam.getCityId())) {
            queryListen.eq(OaDUserInfo.REGISTER_CITY_ID, capacityParam.getCityId());
        }

        queryListen.select(OaDUserInfo.DRIVER_ID);

        List<OaDUserInfo> listenCount= oaDUserInfoMapper.selectList(queryListen);

        CapacityResult listenOrderResult=new CapacityResult();
        listenOrderResult.setType(ECapacityType.listenDriver.getType());
        listenOrderResult.setName(ECapacityType.listenDriver.getValue());
        listenOrderResult.setValue(listenCount.size());

        resultList.add(this.proportion(listenOrderResult, driveCountResult));

        // 统计活跃司机
        Integer activeCount=0;

        if(!listenCount.isEmpty()){
            for(OaDUserInfo userInfo:listenCount){
                String key = RedisPrefixConstant.GPS_VEH_KEY_PREFIX + userInfo.getDriverId();
                if (redisCommon.hashKey(key)) {
                    activeCount ++ ;
                }
            }
        }

        // 接驾中司机量
        resultList.add(this.proportion(this.pickUpACar(capacityParam), driveCountResult));

        // 服务中司机量
        resultList.add(this.proportion(this.service(capacityParam), driveCountResult));

        // 未出车司机量
        resultList.add(this.noDrivingOut(capacityParam));


        // 活跃司机数
        CapacityResult activeResult=new CapacityResult();
        activeResult.setName(MessageConstant.ACTIVE_DRIVER_PROMPT);
        activeResult.setValue(activeCount);
        activeResult.setType(ECapacityType.activeDriver.getType());
        summerResults.add(activeResult);

        // resultList.add(this.enquiry()); 询价司机量

        // 今日出车司机
        summerResults.add(driveOut);

        // 今日完单司机
        summerResults.add(this.orderFulfillment(capacityParam));

        Map<String, List> resultMap = new HashMap<>(2);
        resultMap.put("cake", resultList);
        resultMap.put("summer", summerResults);

        return Rv.wrap(resultMap);
    }

    /**
     * 保存运力数据
     */
    @Override
    public void getSaveCapacityStatistical() {
        QueryWrapper<OaDUserInfo> queryListen = new QueryWrapper<>();
        queryListen.select(OaDUserInfo.DRIVER_ID);
        queryListen.eq(OaDUserInfo.ACCEPTANC_ORDER_STATUS, ParameterEnum.ONE.getType());
        List<OaDUserInfo> userInfoList= oaDUserInfoMapper.selectList(queryListen);
        Integer activeCount=0;
        if(!userInfoList.isEmpty()){
            for(OaDUserInfo user:userInfoList){
                String key = RedisPrefixConstant.GPS_VEH_KEY_PREFIX + user.getDriverId();
                if (redisCommon.hashKey(key)) {
                    activeCount=activeCount+1;
                }
            }
        }
        Date date=new Date();
        CollectCapacityStatistical statistical=new CollectCapacityStatistical();
        statistical.setCollectId(IDUtil.nextId());
        statistical.setDriverActiveNumber(activeCount);
        statistical.setDriverOrderNumber(userInfoList.size());
        statistical.setTag("lhy");
        statistical.setCreateTime(date);
        statistical.setCreateUser(1L);
        statistical.setUpdateTime(date);
        statistical.setUpdateUser(1L);
        collectCapacityStatisticalMapper.insert(statistical);
    }


    /**
     * 获取运力数据趋势折线集
     * @return
     */
    @Override
    public Rv getHistoryCapacityStatistical(CapacityParam capacityParam) {

        if (CheckUtil.objIsEmpty(capacityParam)) {
            throw PangException.create(EErrorCode.missingArg);
        }

        Integer type = this.chartType(capacityParam.getTimeList());

        capacityParam.setChartType(type);

        // 如果为日活司机统计，做特殊处理（按日制组合）
        if (capacityParam.getCapacityType().equals(ECapacityOption.DAILY_ACTIVITY.getKey())) {
            capacityParam.setChartType(2);
        }

        TransportCapacityLineChart transportCapacityLineChart = null;

        Double dateRange = DateUtil.dateSubtractDay(capacityParam.getTimeList().get(0).getTime(), capacityParam.getTimeList().get(1).getTime());

        try {
            transportCapacityLineChart = new TransportCapacityLineChart(capacityParam.getTimeList().get(0), capacityParam.getChartType(), dateRange);
        } catch (Exception e) {
            throw PangException.create(EErrorCode.dateFormatErr);
        }

        switch (capacityParam.getCapacityType()) {
            case 1:
                // 出车司机数
                transportCapacityLineChart = this.driveOutCountLineChart(transportCapacityLineChart, capacityParam);
                break;
            case 2:
                // 应答司机数
                transportCapacityLineChart = this.answerDriverCountLineChart(transportCapacityLineChart, capacityParam);
                break;
            case 3:
                // 完单司机数
                transportCapacityLineChart = this.orderFulfillmentCountLineChart(transportCapacityLineChart, capacityParam);
                break;
            case 4:
                // 人均出车时长
                transportCapacityLineChart = this.drivingTimeCountLineChart(transportCapacityLineChart, capacityParam);
                break;
            case 5:
                // 日活跃司机数
                transportCapacityLineChart = this.dailyActiveDriverCountLineChart(transportCapacityLineChart, capacityParam, dateRange);
                break;
            case 6:
                // tph
                transportCapacityLineChart = this.TPHCountLineChart(transportCapacityLineChart, capacityParam);
                break;
            case 7:
                // iph
                transportCapacityLineChart = this.IPHCountLineChart(transportCapacityLineChart, capacityParam);
                break;
            default:
                throw PangException.create(EErrorCode.mainType);
        }

        transportCapacityLineChart.setName(ECapacityOption.value(capacityParam.getCapacityType()));

        return Rv.wrap(transportCapacityLineChart);
    }

    /**
     * 今日出车司机
     */
    private CapacityResult driveOutAccount(CapacityParam capacityParam) {
        List<Long> driveOutAccount = collectCapacityStatisticalMapper.driveOutAccount(capacityParam);

        CapacityResult driveOutResult = new CapacityResult();
        driveOutResult.setType(ECapacityType.driveOut.getType());
        driveOutResult.setName(ECapacityType.driveOut.getValue());
        driveOutResult.setValue(driveOutAccount.size());

        log.info("今日出车司机数量：{}", driveOutAccount);

        return driveOutResult;
    }

    /**
     * 今日完单司机
     */
    private CapacityResult orderFulfillment(CapacityParam capacityParam) {
        Integer orderFulfillment = collectCapacityStatisticalMapper.orderFulfillmentAccount(capacityParam).size();

        CapacityResult orderFulfillmentResult = new CapacityResult();
        orderFulfillmentResult.setType(ECapacityType.orderFulfillment.getType());
        orderFulfillmentResult.setName(ECapacityType.orderFulfillment.getValue());
        orderFulfillmentResult.setValue(orderFulfillment);

        log.info("今日完单司机数量：{}", orderFulfillment);

        return orderFulfillmentResult;
    }

    /**
     * 未出车司机
     */
    private CapacityResult noDrivingOut(CapacityParam capacityParam) {
        Integer noDrivingOut = collectCapacityStatisticalMapper.noDrivingOutAccount(capacityParam);

        CapacityResult noDrivingOutResult = new CapacityResult();
        noDrivingOutResult.setType(ECapacityType.noDrivingOut.getType());
        noDrivingOutResult.setName(ECapacityType.noDrivingOut.getValue());
        noDrivingOutResult.setValue(noDrivingOut);

        log.info("今日未出车司机数量：{}", noDrivingOut);

        return noDrivingOutResult;
    }

    /**
     * 接驾中司机
     */
    private CapacityResult pickUpACar(CapacityParam capacityParam) {
        Integer pickUpACar = collectCapacityStatisticalMapper.pickUpACarAccount(capacityParam);

        CapacityResult pickUpACarResult = new CapacityResult();
        pickUpACarResult.setType(ECapacityType.pickUpACar.getType());
        pickUpACarResult.setName(ECapacityType.pickUpACar.getValue());
        pickUpACarResult.setValue(pickUpACar);

        log.info("接驾中司机数量：{}", pickUpACar);

        return pickUpACarResult;
    }

    /**
     * 服务中司机
     */
    private CapacityResult service(CapacityParam capacityParam) {
        Integer service = collectCapacityStatisticalMapper.serviceAccount(capacityParam);

        CapacityResult serviceResult = new CapacityResult();
        serviceResult.setType(ECapacityType.service.getType());
        serviceResult.setName(ECapacityType.service.getValue());
        serviceResult.setValue(service);

        log.info("服务中司机数量：{}", service);

        return serviceResult;
    }

    /**
     * 计算占比
     */
    private CapacityResult proportion(CapacityResult capacityResult, CapacityResult driveOutResult) {

        Float driveOutAccount = Float.valueOf(String.valueOf(driveOutResult.getValue()));
        Float result = capacityResult.getValue() / driveOutAccount;

        // 保留1位小数 （全舍）
        String resultStr = String.format("%.1f", result * 100);

        if (capacityResult.getValue() != 0 && driveOutAccount != 0) {
            capacityResult.setProportion(resultStr + "%");
        } else {
            capacityResult.setProportion("0.0%");
        }

        log.info("占比计算：{} / {} = {}", capacityResult.getValue(), driveOutAccount, capacityResult.getProportion());
        log.info("最终占比：{}%", capacityResult.getProportion());

        return capacityResult;
    }

    /**
     * 出车司机折线集
     */
    private TransportCapacityLineChart driveOutCountLineChart(TransportCapacityLineChart transportCapacityLineChart, CapacityParam capacityParam) {

        List<Map<String, Object>> resultMap = capacitySearchService.getDriveOutLineChart(capacityParam);

        // 汇总结果集
        return this.summary(transportCapacityLineChart, resultMap);
    }

    /**
     * 应答司机折线集
     */
    private TransportCapacityLineChart answerDriverCountLineChart(TransportCapacityLineChart transportCapacityLineChart, CapacityParam capacityParam) {

        Integer select = capacityParam.getChartType();
        List<Map<String, Object>> resultMap = new ArrayList<>();

        switch (select) {
            case 1:
                // 30 日制应答司机数
                resultMap = collectCapacityStatisticalMapper.answerDriverCountDayLineChart(capacityParam.getTimeList(), capacityParam.getCityId());
                break;
            case 2:
                // 7 日制应答司机数
                resultMap = collectCapacityStatisticalMapper.answerDriverCountDayLineChart(capacityParam.getTimeList(), capacityParam.getCityId());
                break;
            case 3:
                // 24 时制应答司机数
                resultMap = collectCapacityStatisticalMapper.answerDriverCountTimeLineChart(capacityParam.getTimeList(), capacityParam.getCityId());
                break;
            default:
                throw PangException.create(EErrorCode.mainType);
        }

        // 汇总结果集
        return this.summary(transportCapacityLineChart, resultMap);

    }

    /**
     * 完单司机折线集
     */
    private TransportCapacityLineChart orderFulfillmentCountLineChart(TransportCapacityLineChart transportCapacityLineChart, CapacityParam capacityParam) {

        Integer select = capacityParam.getChartType();
        List<Map<String, Object>> resultMap = new ArrayList<>();

        switch (select) {
            case 1:
                // 30 日制完单司机
                resultMap = collectCapacityStatisticalMapper.orderFulfillmentCountLineChart(capacityParam.getTimeList(), capacityParam.getCityId());
                break;
            case 2:
                // 7 日制完单司机
                resultMap = collectCapacityStatisticalMapper.orderFulfillmentCountLineChart(capacityParam.getTimeList(), capacityParam.getCityId());
                break;
            case 3:
                // 24 时制完单司机
                resultMap = collectCapacityStatisticalMapper.orderFulfillmentToDayCountLineChart(capacityParam.getTimeList(), capacityParam.getCityId());
                break;
            default:
                throw PangException.create(EErrorCode.mainType);
        }

        // 汇总结果集
        return this.summary(transportCapacityLineChart, resultMap);
    }

    /**
     * 总出车时长
     */
    private TransportCapacityLineChart drivingTimeSumLineChart(TransportCapacityLineChart transportCapacityLineChart, CapacityParam capacityParam) {

        Integer select = capacityParam.getChartType();
        List<Map<String, Object>> resultMap = new ArrayList<>();

        switch (select) {
            case 1:
                // 30 日制总出车时长
                resultMap = collectCapacityStatisticalMapper.getDrivingTimeSumLineChart(capacityParam.getTimeList(), capacityParam.getCityId());
                break;
            case 2:
                // 7 日制总出车时长
                resultMap = collectCapacityStatisticalMapper.getDrivingTimeSumLineChart(capacityParam.getTimeList(), capacityParam.getCityId());
                break;
            case 3:
                // 24 时制总出车时长
                resultMap = collectCapacityStatisticalMapper.getDrivingTimeToDaySumLineChart(capacityParam.getTimeList(), capacityParam.getCityId());
                break;
            default:
                throw PangException.create(EErrorCode.mainType);
        }

        // 汇总结果集
        return this.summary(transportCapacityLineChart, resultMap);
    }

    /**
     * 人均出车时长
     */
    private TransportCapacityLineChart drivingTimeCountLineChart(TransportCapacityLineChart transportCapacityLineChart, CapacityParam capacityParam) {

        Integer select = capacityParam.getChartType();
        List<Map<String, Object>> resultMap = new ArrayList<>();
        List<Map<String, Object>> summerMap = new ArrayList<>();

        switch (select) {
            case 1:
            case 2:
                // 30 日制人均出车时长
                // 7 日制人均出车时长
                summerMap = collectCapacityStatisticalMapper.getDrivingTimeCountLineChart(capacityParam.getTimeList(), capacityParam.getCityId());

                List<Map<String, Object>> countMap = new ArrayList<>();

                List<String> driverIdList = new ArrayList<>();

                for (Map<String, Object> timeMap : summerMap) {

                    if (CheckUtil.collectionIsEmpty(countMap)) {
                        Map<String, Object> count = new HashMap<>();
                        count.put("time", timeMap.get("time"));
                        count.put("account", timeMap.get("account"));

                        driverIdList.add(timeMap.get("driverId").toString());

                        count.put("count", 1);
                        countMap.add(count);
                    } else {

                        int num = 0;

                        for (Map<String, Object> driverMap : countMap) {
                            String time = driverMap.get("time").toString();
                            if (time.equals(timeMap.get("time").toString())) {
                                // 若时间相等则增加count数量

                                int driverNum = 0;

                                for (String dId : driverIdList) {
                                    if (!(dId.equals(timeMap.get("driverId").toString()))) {
                                        driverNum ++;
                                    }
                                }

                                if (driverNum == driverIdList.size()) {
                                    driverMap.put("count", Integer.parseInt(driverMap.get("count").toString()) + 1);
                                    driverIdList.add(timeMap.get("driverId").toString());
                                }

                                BigDecimal timeAccount = BigDecimal.valueOf(0.00);
                                BigDecimal driverAccount = BigDecimal.valueOf(0.00);

                                if (CheckUtil.objIsNotEmpty(timeMap.get("account"))) {
                                    timeAccount = new BigDecimal(timeMap.get("account").toString());
                                }

                                if (CheckUtil.objIsNotEmpty(driverMap.get("account"))) {
                                    driverAccount = new BigDecimal(driverMap.get("account").toString());
                                }

                                driverMap.put("account", timeAccount.add(driverAccount));
                            } else {
                                num ++;
                            }

                            if (num == countMap.size()) {
                                Map<String, Object> count = new HashMap<>();
                                count.put("time", timeMap.get("time"));
                                count.put("account", timeMap.get("account"));
                                count.put("count", 1);
                                countMap.add(count);

                                driverIdList = new ArrayList<>();
                                driverIdList.add(timeMap.get("driverId").toString());

                                break;
                            }

                        }

                    }
                }

                for (Map<String, Object> result : countMap) {

                    BigDecimal timeAccount = BigDecimal.valueOf(0.00);

                    if (CheckUtil.objIsNotEmpty(result.get("account"))) {
                        timeAccount = new BigDecimal(result.get("account").toString());
                    }

                    BigDecimal driverCount = BigDecimal.valueOf(0.00);

                    if (CheckUtil.objIsNotEmpty(result.get("count"))) {
                        driverCount = new BigDecimal(result.get("count").toString());
                    }

                    BigDecimal accountDecimal = timeAccount;
                    BigDecimal countDecimal = driverCount;

                    result.put("account", accountDecimal.divide(countDecimal, 2, BigDecimal.ROUND_HALF_UP));
                    result.remove("count");
                    result.remove("driverId");

                }

                resultMap = countMap;
                break;
            case 3:
                // 24 时制人均出车时长
                resultMap = collectCapacityStatisticalMapper.getDrivingTimeToDayCountLineChart(capacityParam.getTimeList(), capacityParam.getCityId());
                break;
            default:
                throw PangException.create(EErrorCode.mainType);
        }

        // 汇总结果集
        return this.summary(transportCapacityLineChart, resultMap);
    }

    /**
     * 日活跃司机数
     */
    private TransportCapacityLineChart dailyActiveDriverCountLineChart(TransportCapacityLineChart transportCapacityLineChart, CapacityParam capacityParam, Double dateRange) {
        List<Map<String, Object>> resultMap = new ArrayList<>();

        List<ActiveDriver> activeDrivers = null;

        if (dateRange <= 1) {

            Set<Map<String, String>> mapSet = redisTemplate.opsForSet().members(RedisPrefixConstant.DRIVER_ACTIVE);

            if (CheckUtil.objIsEmpty(capacityParam.getCityId())) {

                Map<String, Object> map = new HashMap<>(2);
                map.put("time", DateUtil.convertToStringCustom(capacityParam.getTimeList().get(1), "MM-dd"));
                map.put("account", mapSet.size());
                resultMap.add(map);

                // 日活司机去掉昨日数据
                List<String> granularity = new ArrayList<>(transportCapacityLineChart.getGranularity());
                granularity.remove(0);
                transportCapacityLineChart.setGranularity(granularity);

                return this.summary(transportCapacityLineChart, resultMap);

            } else {

                Integer activeDriverSize = 0;
                if (CheckUtil.collectionIsNotEmpty(mapSet)) {
                    for (Map<String, String> map : mapSet) {
                        if (map.get("adcode").equals(capacityParam.getCityId())) {
                            activeDriverSize ++;
                        }
                    }
                }

                Map<String, Object> map = new HashMap<>(2);
                map.put("time", DateUtil.convertToStringCustom(capacityParam.getTimeList().get(1), "MM-dd"));
                map.put("account", activeDriverSize);
                resultMap.add(map);

                // 日活司机去掉昨日数据
                List<String> granularity = new ArrayList<>(transportCapacityLineChart.getGranularity());
                granularity.remove(0);
                transportCapacityLineChart.setGranularity(granularity);

                return this.summary(transportCapacityLineChart, resultMap);
            }
        } else {

            resultMap = capacitySearchService.getActiveDriver(capacityParam);

            if (resultMap.size() > 0) {
                Set<Map<String, String>> mapSet = redisTemplate.opsForSet().members(RedisPrefixConstant.DRIVER_ACTIVE);

                resultMap.get(resultMap.size() - 1).put("account", mapSet.size());
            }

        }

        // 汇总结果集
        return this.summary(transportCapacityLineChart, resultMap);
    }

    /**
     * tph
     */
    private TransportCapacityLineChart TPHCountLineChart(TransportCapacityLineChart transportCapacityLineChart, CapacityParam capacityParam) {

        TransportCapacityLineChart orderFulfillment = null;
        // 完单司机量
        orderFulfillment = this.orderFulfillmentCountLineChart(new TransportCapacityLineChart(capacityParam.getTimeList().get(0), capacityParam.getChartType(), DateUtil.dateSubtractDay(capacityParam.getTimeList().get(0).getTime(), capacityParam.getTimeList().get(1).getTime())), capacityParam);

        TransportCapacityLineChart drivingTime = null;
        // 总出车时长
        drivingTime = this.drivingTimeSumLineChart(new TransportCapacityLineChart(capacityParam.getTimeList().get(0), capacityParam.getChartType(), DateUtil.dateSubtractDay(capacityParam.getTimeList().get(0).getTime(), capacityParam.getTimeList().get(1).getTime())), capacityParam);

        // 汇总结果集
        return this.PHCalculation(orderFulfillment, drivingTime, capacityParam);
    }

    /**
     * iph
     */
    private TransportCapacityLineChart IPHCountLineChart(TransportCapacityLineChart transportCapacityLineChart, CapacityParam capacityParam) {

        TransportCapacityLineChart orderFulfillment = null;
        // 结算流水
        orderFulfillment = orderSummaryService.orderFlowToDayChart(new TransportCapacityLineChart(capacityParam.getTimeList().get(0), capacityParam.getChartType(), DateUtil.dateSubtractDay(capacityParam.getTimeList().get(0).getTime(), capacityParam.getTimeList().get(1).getTime())), capacityParam);

        TransportCapacityLineChart drivingTime = null;
        // 总出车时长
        drivingTime = this.drivingTimeSumLineChart(new TransportCapacityLineChart(capacityParam.getTimeList().get(0), capacityParam.getChartType(), DateUtil.dateSubtractDay(capacityParam.getTimeList().get(0).getTime(), capacityParam.getTimeList().get(1).getTime())), capacityParam);

        return this.PHCalculation(orderFulfillment, drivingTime, capacityParam);
    }

    /**
     * * PH计算
     */
    private TransportCapacityLineChart PHCalculation(TransportCapacityLineChart orderFulfillment, TransportCapacityLineChart drivingTime, CapacityParam capacityParam) {

        List<BigDecimal> PHList = new ArrayList<>();

        TransportCapacityLineChart PHProp = new TransportCapacityLineChart(capacityParam.getTimeList().get(0), capacityParam.getChartType(), DateUtil.dateSubtractDay(capacityParam.getTimeList().get(0).getTime(), capacityParam.getTimeList().get(1).getTime()));

        for (int i = 0; i < drivingTime.getGranularity().size(); i++) {
            BigDecimal drivingTimeAvg = drivingTime.getCollection().get(i);
            BigDecimal orderFulfillmentAvg = orderFulfillment.getCollection().get(i);

            BigDecimal zero = BigDecimal.valueOf(0.00);

            if (orderFulfillmentAvg.compareTo(zero) != 0 && drivingTimeAvg.compareTo(zero) != 0) {
                BigDecimal divideResult = orderFulfillmentAvg.divide(drivingTimeAvg, 2, BigDecimal.ROUND_HALF_UP);
                log.info("{} / {} = {}", orderFulfillmentAvg, drivingTimeAvg, divideResult);
                PHList.add(divideResult);
            } else {
                PHList.add(zero);
            }

        }

        PHProp.setCollection(PHList);

        return PHProp;
    }

    /**
     * 汇总结果集
     */
    @Override
    public TransportCapacityLineChart summary(TransportCapacityLineChart transportCapacityLineChart, List<Map<String, Object>> resultMap) {
        transportCapacityLineChart.setCollection(new ArrayList<>());
        for (String granularity : transportCapacityLineChart.getGranularity()) {
            if (CheckUtil.objIsEmpty(granularity)) {
                break;
            }
            int f = 0;
            for (Map<String, Object> result : resultMap) {
                // 如果为空则跳出
                if (CheckUtil.objIsEmpty(result.get("time"))) {
                    transportCapacityLineChart.getCollection().add(BigDecimal.valueOf(0.00));
                    continue;
                }
                // 如果为空则跳出
                if (CheckUtil.objIsEmpty(result.get("account"))) {
                    transportCapacityLineChart.getCollection().add(BigDecimal.valueOf(0.00));
                    continue;
                }
                // 计算
                String time = result.get("time").toString();
                time = time.substring(time.indexOf('|') + 1);
                if (granularity.equals(time)) {
                    transportCapacityLineChart.getCollection().add(new BigDecimal(result.get("account").toString().replaceAll(",", "")));
                    break;
                } else {
                    f ++;
                }
            }
            if (f == resultMap.size()) {
                transportCapacityLineChart.getCollection().add(BigDecimal.valueOf(0.00));
            }
        }
        return transportCapacityLineChart;
    }

    /**
     * value格式化
     */
    private CapacityResult formatValue(CapacityResult capacityResult) {
        /*capacityResult.setValue(this.appendString(capacityResult.getValue(), "人"));*/
        return capacityResult;
    }

    /**
     * 字符串拼接
     */
    private String appendString(Object old, String concat) {
        StringBuffer stringBuffer = new StringBuffer(old.toString()).append(concat);
        return stringBuffer.toString();
    }

    /**
     * 计算ChartType
     */
    @Override
    public Integer chartType(List<Date> dates) {
        double d = DateUtil.dateSubtractBuffer(dates.get(1).getTime(), dates.get(0).getTime());
        double time = d / 60 / 24;
        int type = 0;
        if (time <= 1) {
            type = 3;
        } else if (time <= 7) {
            type = 2;
        } else {
            type = 1;
        }
        return type;
    }

    /**
     * 旧版运力折线集汇总
     */
    private void old() {
        /*List<Date> timeList=capacityParam.getTimeList();
        if(!timeList.isEmpty()){
            if(timeList.size()==2){
                if(CheckUtil.objIsNotEmpty(timeList.get(0))){
                    capacityParam.setStartTime(timeList.get(0));
                }
                if(CheckUtil.objIsNotEmpty(timeList.get(1))) {
                    capacityParam.setEndTime(timeList.get(1));
                }
            }else{
                throw PangException.create(EErrorCode.missingArg);
            }
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date zero = calendar.getTime();
        QueryWrapper<CollectCapacityStatistical> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(CollectCapacityStatistical.CREATE_TIME,CollectCapacityStatistical.DRIVER_ACTIVE_NUMBER,CollectCapacityStatistical.DRIVER_ORDER_NUMBER);
        if(CheckUtil.objIsNotEmpty(capacityParam.getStartTime())){
            queryWrapper.ge(OaCOrderPersonal.CREATE_TIME, capacityParam.getStartTime());
        }else{
            queryWrapper.ge(OaCOrderPersonal.CREATE_TIME, zero);
        }
        if(CheckUtil.objIsNotEmpty(capacityParam.getEndTime())) {
            queryWrapper.le(OaCOrderPersonal.CREATE_TIME, capacityParam.getEndTime());
        }else{
            queryWrapper.le(OaCOrderPersonal.CREATE_TIME, new Date());
        }
        List<CollectCapacityStatistical> statisticalList= collectCapacityStatisticalMapper.selectList(queryWrapper);
        Map<String, Object> resultMap = new HashMap<>(16);
        List<Object> dateList = new ArrayList<>();
        List<Integer> orderNumberList = new ArrayList<>();
        List<Integer> activeNumberList = new ArrayList<>();
        if(!statisticalList.isEmpty()){
            for(CollectCapacityStatistical statistical:statisticalList){
                dateList.add(new DateToStringConverter().convertFoMonth(statistical.getCreateTime()));
                orderNumberList.add(statistical.getDriverOrderNumber());
                activeNumberList.add(statistical.getDriverActiveNumber());
            }
        }
        if(dateList.isEmpty()){
            Calendar cal = Calendar.getInstance();
            int month = cal.get(Calendar.MONTH);
            int day = cal.get(Calendar.DATE);
            dateList.add(month+"-"+day+" "+"00:00");
        }
        resultMap.put("dateList", dateList);
        resultMap.put("orderNumberList", orderNumberList);
        resultMap.put("activeNumberList", activeNumberList);
        return Rv.wrap(EErrorCode.success,resultMap);*/
    }

}
